<template>
  <div class="editkuwei">
    <el-dialog :visible.sync="centerDialogVisible"
               :close-on-click-modal="clickModalHide"
               :before-close="closeDialog" width="390px"
               :title="type=='add'?'新增库位':'修改库位'">
      <el-form :model="editData" size="mini" status-icon :rules="rules" ref="editData" label-width="100px"
               class="demo-ruleForm">
        <el-form-item label="工段：" prop="gqId">
          <el-select v-model="editData.gqId" filterable placeholder="请选择" disabled @change="changeGw">
            <el-option
              v-for="item in gongquList"
              :key="item.id"
              :label="item.gqName"
              :value="item.id">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="工装：" prop="gwId">
          <el-select v-model="editData.gzId" :disabled="type =='edit'" filterable placeholder="请选择" @change="changeGz">
            <el-option
              v-for="item in gongWei"
              :key="item.id"
              :label="item.name"
              :value="item.id">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="库号：" prop="khNum">
          <el-select v-model="editData.khNum" :disabled="type =='edit'" filterable placeholder="请选择字母" >
            <el-option
              v-for="item in khNumList"
              :key="item"
              :label="item"
              :value="item">
            </el-option>
          </el-select>
          <!--<el-input :disabled="type =='edit'" v-model="editData.khNum" style="width: 72%;" placeholder="请输入字母"></el-input>-->
        </el-form-item>
        <!--<el-form-item label="库位数">-->
          <!--<el-input-number v-model="kwNum"  :min="1" :max="9" label="描述文字"></el-input-number>-->
        <!--</el-form-item>-->
      </el-form>
      <div style="text-align: right" class="ku_wei">
        <i class="fa fa-plus-circle" aria-hidden="true" style="cursor: pointer;margin-right: 5px" @click="addPosition"></i>
        <i class="fa fa-minus-circle" aria-hidden="true" style="cursor: pointer" @click="deletePosition"></i>
      </div>
      <div class="scroll-div">
        <wh-table :tableData="tableData"  :filterPage="false" :tableLoading="tableLoading" :tableHeader="tableHeader" :option="option" ></wh-table>
      </div>

      <div style="text-align: center;margin-top: 15px">
        <el-button type="primary" @click="submitForm('editData')">提交</el-button>
        <el-button @click="resetForm('editData')">取消</el-button>
      </div>
    </el-dialog>
  </div>
</template>
<script>
  import whTable from "../../../components/wh-table/index";
  import {getAlphabet} from '@/utils/common.js'
  import {sortStr} from '@/utils/common.js'

  export default {
    name: 'editGq',
    props: ['dataDetail','allKuWeiList','type'],
    data() {
      var notEmpty = (rule, value, callback) => {
        if (!value) {
          return callback(new Error('不能为空'));
        } else {
          callback();
        }
      };

      var notRepeat = (rule, value, callback) => {
        if (!value) {
          return callback(new Error('不能为空'));
        } else {
          if(!/^[A-Z]+$/.test(value)&&value.length !=1){
            return callback(new Error('请输入一位大写字母'));
          }
          for(let qw of this.gongWei){
            if(value == qw.gwCode && qw.id!=this.editData.id){
              return callback(new Error('工位代码已经存在'));
            }
          }
          callback();
        }
      };
      return {
        centerDialogVisible: false,
        clickModalHide: false,
        gongquList: [],
        gongWei: [],
        gongWeiMap: {},
        editData: {
          gqId: "",
          gzId: "",
          khNum: "",
        },
        kwNum:99,
        rules: {
          id: [
            {validator: notEmpty, trigger: 'blur'}
          ],
          gwName: [
            {validator: notEmpty, trigger: 'blur'}
          ],
          gwCode: [
            {validator: notRepeat, trigger: 'blur'}
          ],
          gqId: [
            {validator: notEmpty, trigger: 'blur'}
          ]
        },
        count: 0,

        tableData: [],
        tableHeader:[],
        tableLoading:true,
        pMap:{},
        option:{showOperate:false,headerCell:{background:'rgb(108,198,236)',color:'#000000cc'}},

        khNumList:["A","B","C","D","E","F","G","H","I","J","K","L","M","N","O","P","Q","R","S","T","U","V","W","X","Y","Z"]
      }
    },

    components:{
      whTable
    },

    mounted() {
      this.getGongQu();
      this.getGongZhuangName();
      this.setAddKuWeiHeader();
    },

    methods: {

      addPosition(){
        if(!this.editData.gqId){
          this.notifyMsg("工段不能为空！");
          return;
        }
        if(!this.editData.gzId){
          this.notifyMsg("工装不能为空！");
          return;
        }
        if(!this.editData.khNum){
          this.notifyMsg("库号不能为空！");
          return;
        }
        if(this.allKuWeiList && this.allKuWeiList.length > 0){
          let kuWei = this.allKuWeiList.find(item=> item.id == this.editData.gqId);
          if(kuWei){
            let gwCode = (this.gongWei.find(item=>item.id == this.editData.gzId)).code;
            let data = {khNum:this.editData.khNum,code:"",name:"",gzId:this.editData.gzId};
            let maxNum = "1";
            if(this.pMap.hasOwnProperty(this.editData.khNum)){
              let values = this.pMap[this.editData.khNum];
              for(let _v of values){
                let secondNum = _v.substring(1,_v.length);
                maxNum = secondNum;
              }
              maxNum = values.length == 0?maxNum:(parseInt(maxNum)+1)+"";
              if(parseInt(maxNum) >= (this.kwNum+1)){
                this.notifyMsg("库位数不能超过99！");
                return;
              }
              data.name = this.editData.khNum+maxNum;
              data.code = gwCode+this.editData.khNum+data.name;
            }else{
              data.name = this.editData.khNum+maxNum;
              data.code = gwCode+this.editData.khNum+data.name;
            }

            this.pMap[data.khNum] = this.pMap[data.khNum]||[];
            this.pMap[data.khNum].push(data.name);
            this.tableData.push(data)
          }
        }
      },

      deletePosition(){
        let deletePosition = this.tableData.pop();
        let names = this.pMap[deletePosition.khNum];
        names.splice(names.indexOf(deletePosition.name),1);
      },

      initPMap(){
        this.pMap = {};
        let kuWei = this.allKuWeiList.find(item=> item.id == this.editData.gqId);
        let positionHousesList = kuWei?kuWei.positionHousesList:[];
        if(positionHousesList && positionHousesList.length > 0){
          let filterPosition = positionHousesList.filter(item=>item.gzId ==this.editData.gzId);
          if(filterPosition && filterPosition.length > 0){
            for(let _data of filterPosition){
              this.pMap[_data.khNum] = this.pMap[_data.khNum]?this.pMap[_data.khNum]:[];
              this.pMap[_data.khNum].push(_data.name);
            }
          }
        }
      },


      notifyMsg(msg,type){
        this.$notify({
          title: '提示',
          message: msg,
          type:type?type:'warning'
        });
      },

      setAddKuWeiHeader(){
        this.tableHeader = [{"columnName": "khNum", "coloumNameCn": "库号"},
          {"columnName": "name", "coloumNameCn": "库位"},
          {"columnName": "code", "coloumNameCn": "库位代码"},];
      },

      operatePositionHouse() {
        let self = this;
        let url = this.type == 'add'?'/autoMonitor/position/addPositionHouse':'/autoMonitor/position/updatePositionHouse';
        if(self.tableData.length == 0){
          self.$notify({
            title: '提示',
            message: "至少添加一组信息！",
            type: 'error'
          });
          return;
        }
        if (this.count == 0) {
          self.deleteTableNoMeaningAttr();
          self.$http({
            url: url,
            method: "post",
            data: JSON.stringify(self.tableData),
            dataType: 'json',
            contentType: "application/json"
          }).then(resp => {
            if (resp.success) {
              self.resetForm('editData');
              self.$eventBus.$emit("updateKuWei");
              self.$notify({
                title: '提示',
                message: "修改成功！",
                type: 'success'
              });
              return
            }else{
              self.$notify({
                title: '提示',
                message: "库位冲突！请核查",
                type: 'warning'
              });
            }
            this.count--;
          });
          this.count++;
        }
      },

      //关闭弹窗
      closeDialog() {
        this.$refs['editData'].clearValidate();
        this.centerDialogVisible = false;
      },

      submitForm(formName) {
        let self = this;
        this.$refs[formName].validate((valid) => {
          if (valid) {
            self.operatePositionHouse();
          } else {
            return false;
          }
        });
      },
      resetForm(formName) {
        this.$refs[formName].clearValidate();
        this.closeDialog();
      },

      changeGw() {
        let self = this;
        self.editData.gzId = "";
        self.gongWei = self.gongWeiMap[self.editData.gqId];
      },

      changeGz(){
        this.initPMap();
      },

      getGongQu() {
        let self = this;
        self.$http({
          url: "/autoMonitor/position/queryAllGq",
          method: "post",
        }).then(resp => {
          if (resp.success) {
            self.gongquList = resp.result;
          }
        });
      },

      deleteTableNoMeaningAttr(){
        for(let data of this.tableData){
          delete data.createTime;
          delete data.count;
        }
      },

      getGongZhuangName() {
        let self = this;
        self.$http({
          url: "/autoMonitor/gz/queryGzName",
          method: "post",
        }).then(resp => {
          if (resp.success) {
            for (let data of resp.result) {
              let children = self.gongWeiMap[data.gqId] ? self.gongWeiMap[data.gqId] : [];
              children.push(data);
              self.gongWeiMap[data.gqId] = children;
            }
          }
        });
      },

    },
    watch: {
      dataDetail(val) {
        let self = this;
        this.count = 0;
        // this.kwNum = 9;
        this.centerDialogVisible = true;
        for (let key in this.editData) {
          if (!val.hasOwnProperty(key)) {
            val[key] = "";
          }
        }
        this.editData = val;
        self.$nextTick(()=>{
          self.tableData = [];
          if(this.type == 'edit'){
            let kuWei = this.allKuWeiList.find(item=> (item.id == self.editData.gqId));
            if(kuWei && kuWei.positionHousesList){
               let positionHousesList = kuWei.positionHousesList.filter(item=> (item.gzCode == self.editData.gzCode && item.khNum == self.editData.khNum));
               self.tableData = JSON.parse(JSON.stringify(positionHousesList));
               // self.tableData = sortStr(self.tableData,"name");
            }
          }
          self.tableLoading = false;
        });
        if(this.type == 'edit'){
          this.initPMap();
        }
        this.gongWei = this.gongWeiMap[this.editData.gqId];
      }
    }
  }
</script>
<style scoped>
  .editkuwei .el-dialog__body {
    padding: 0px 20px;
  }

  .editkuwei .el-form-item {
    margin-bottom: 10px;
  }
  .editkuwei .el-button--medium {
    padding: 4px 12px;
    font-size: 12px;
    border-radius: 4px;
  }

  .scroll-div{
    height:200px;
    overflow-x:hidden;
    overflow-y:auto;
  }

  .editkuwei .el-table--medium td, .editkuwei .el-table--medium th {
    padding: 0px 0;
  }

</style>
